package com.guobox.movies.usecase;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.graphics.Palette;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.guobox.movies.APP;
import com.guobox.movies.entity.MovieEntity;
import com.guobox.movies.entity.MovieMedia;
import com.guobox.movies.present.MovieDetailPresent;
import com.guobox.movies.proxy.HttpUrls;
import com.guobox.movies.proxy.Proxy_Server;
import com.guobox.movies.utils.BgColorsUtils;
import com.guobox.movies.utils.httpsutils.OkhttpsUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xuxinlei on 2017/7/4.
 */

public class MovieDetailModelImp implements MovieDetailModel {

    private static final String TAG = "MovieDetailModel";
    private MovieDetailPresent movieDetailPresent;

    public MovieDetailModelImp(MovieDetailPresent movieDetailPresent) {
        this.movieDetailPresent = movieDetailPresent;
    }

    @Override
    public void getMovieDetailFromServer(final MovieEntity movieEntity) {
        final Handler handler = new Handler(Looper.getMainLooper());
        new Thread(){
            @Override
            public void run() {
                Request request = new Request.Builder()
                        .url(HttpUrls.getMoviesMeta(movieEntity.getMetadata().getMovieId()).build())
                        .build();
                OkhttpsUtils.getOkHttpClient().newCall(request)
                        .enqueue(new Callback() {
                            @Override
                            public void onFailure(final Call call, IOException e) {
                                e.printStackTrace();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        movieDetailPresent.MovieDetailCallback(movieEntity);
                                    }
                                });
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                String responseJson = response.body().string();
                                JsonElement responseJsonElement = Proxy_Server.getContent(responseJson);
                                if (responseJsonElement != null) {
                                    JsonElement movieDetailJson = responseJsonElement.getAsJsonArray().get(0);
                                    Gson gson = new Gson();
                                    MovieMedia movieMedia = gson.fromJson(movieDetailJson, MovieMedia.class);
                                    if (movieMedia != null) {
                                        movieEntity.setMetadata(movieMedia);
                                        final String[] colors = formatColors(movieEntity);
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                movieDetailPresent.MovieDetailCallback(movieEntity);
                                                movieDetailPresent.MoviePosterColorCallback(colors);
                                            }
                                        });
                                    }
                                }
                            }
                        });
            }
        }.start();
    }

    private String[] formatColors(MovieEntity movieEntity) {
        String[] colors = null;
        if (!TextUtils.isEmpty(movieEntity.getMetadata().getColors())) {
            colors = movieEntity.getMetadata().getColors().split(",");
            return colors;
        }else{
            Bitmap myBitmap = null;
            try {
                myBitmap = Glide.with(APP.getApplication())
                        .load(HttpUrls.getMoviePosterURL(movieEntity.getMetadata().getMovieId(),HttpUrls.Pic_Middle).build().toString())
                        .asBitmap()
                        .centerCrop()
                        .into(520, 730)
                        .get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            if (myBitmap != null) {
                Palette.Swatch swatch = getPaletteSwatch(myBitmap);
                if (swatch != null) {
                    int color = swatch.getRgb();
                    int red = (color & 0xff0000) >> 16;
                    int green = (color & 0x00ff00) >> 8;
                    int blue = (color & 0x0000ff);

                    String mainColor = BgColorsUtils.paddingColorString(red) + BgColorsUtils.paddingColorString(green) + BgColorsUtils.paddingColorString(blue);
                    colors = new String[]{mainColor, mainColor, mainColor, mainColor, mainColor};
                    return colors;
                }
            }
        }
        return null;

    }
    private Palette.Swatch getPaletteSwatch(Bitmap bitmap) {
        Palette.Builder builder =
                Palette.from(bitmap);
        Palette palette = builder.maximumColorCount(1)
                .generate();
        List<Palette.Swatch> swatches = palette.getSwatches();
        return swatches.size() == 0 ? null : swatches.get(0);
    }
}
